//
//  DHChooseDiseaseViewController.m
//  DHKuaiYi
//
//  Created by  chenhanmao on 2016/11/13.
//  Copyright © 2016年 30-陈辉华. All rights reserved.
//

#import "DHChooseDiseaseViewController.h"
#import <Masonry.h>
#import "DHArrowTableViewCell.h"
#import "DHSelectTableViewCell.h"
#import "UIColor+XHHAddition.h"
#import "DHDoctorApplyViewController.h"
#import "DHDiagnosisTypeViewController.h"
#import "DHComplicationsViewController.h"
#import "DHChooseDiseaseModel.h"
#import "DHDCViewController.h"
#import <SVProgressHUD.h>
#import "NetworkTool.h"
#import <MJRefresh.h>

#define delay(time) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((time) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{[SVProgressHUD dismiss];})
#define delayUpdata(time) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((time) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{[self.tableView.mj_header endRefreshing];[self.tableView.mj_footer endRefreshing];})

static NSString *arrowCellID = @"arrowCell";
static NSString *selectCellID = @"selectCell";

@interface DHChooseDiseaseViewController ()<UITableViewDataSource,UITableViewDelegate>

/**  tableView  */
@property(nonatomic,weak) UITableView *tableView;

/**   是否接受过治疗  */
@property(nonatomic,assign) BOOL isTreated;

/**  治疗方式   */
@property(nonatomic,copy) NSString *diagnosisType;

/**  并发症种类  */
@property(nonatomic,strong) NSArray *complicationsArr;

/**  疾病类型label  */
@property(nonatomic,weak) UILabel *diseaseTypeLabel;

/**  数据源模型数组  */
@property(nonatomic,strong) NSArray <DHChooseDiseaseModel *> *chooseDiseaseList;

/**  匹配到的医生数量   */
@property(nonatomic,weak) UILabel *doctorCountLabel;

/**  疾病细分名字   */
@property(nonatomic,copy) NSString *diseaseDetailType;

/**  网络请求参数  */
@property(nonatomic,strong) NSDictionary *parameters;

@end

@implementation DHChooseDiseaseViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    
    self.parameters = @{@"ci1_id":@1,@"ci2_id":@3,@"ci3_id":@3,@"diagnosis_type":@0,@"is_confirmed":@1,@"user_id":@1000089, @"has_diagnosis":@2};
    
}


#pragma mark - 设置导航栏
- (void)xhhSetupNavigationItems {
    
    [super xhhSetupNavigationItems];
    
    self.title = @"疾病详情选择";
    
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"预约须知" style:UIBarButtonItemStylePlain target:self action:@selector(beSpokenNotice)];
    
    self.navigationItem.rightBarButtonItem = rightBtn;
    
}




#pragma mark - dataSource方法的实现
//  返回组数
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 5;
}

//  返回行数
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

//  返回cell
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *cellID;
    
    if (indexPath.section == 2 || indexPath.section == 3) {
        cellID = selectCellID;
       
    }else{
        cellID = arrowCellID;
    }
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    
    
    DHArrowTableViewCell *selectedCell = (DHArrowTableViewCell *)cell;
    
    selectedCell.chooseDisease = self.chooseDiseaseList[indexPath.section];
    
    if (indexPath.section == 3) {
        DHSelectTableViewCell *selectedCell = (DHSelectTableViewCell *)cell;
        //处理block的循环引用
        __weak typeof(self) weakSelf = self;

        selectedCell.selectedBlock = ^(BOOL isTreated){
            weakSelf.isTreated = isTreated;
        };
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}


#pragma mark - UITableViewDelegate
//组间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 4;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //初始化界面是隐藏治疗方法
    NSIndexPath *tmpPath = [NSIndexPath indexPathForRow:0 inSection:4];
    
    if (indexPath == tmpPath) {
        
        [cell setHidden:YES];
    }
}

//选中某行调用的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        //选择疾病细分
        DHDCViewController *DHDC = [[DHDCViewController alloc] init];
        //准备好block
        void (^myBlock)() = ^(NSString *name){
            
            self.diseaseDetailType = name;
        };
        if (DHDC != nil) {
            DHDC.myBlock = myBlock;
            DHDC.tag = 1;
            NSLog(@"%zd",self.index);
            DHDC.ID = @(self.index + 1);
            int arr[] = {1,1,2,2,4};
            DHDC.num = (NSUInteger)arr[self.index];
        }
        
        [self.navigationController pushViewController:DHDC animated:YES];
        
    }else if (indexPath.section == 1) {
        
        if (self.diseaseDetailType == nil) {
            //调用第三方弹出提示框
            [SVProgressHUD showErrorWithStatus:@"请先选择疾病细分"];
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
            delay(1.0);
            return;
        }
        
        //选择并发症
        DHComplicationsViewController *comVC = [[DHComplicationsViewController alloc] init];
        
        __weak typeof(self) weakSelf = self;
        //回调选中的并发症
        comVC.complicationsBlcok = ^(NSArray *complicationsArr){
            
            weakSelf.complicationsArr = complicationsArr;
        };
        [self.navigationController pushViewController:comVC animated:YES];
        
        
    }else if (indexPath.section == 4) {
        
        //选择治疗方法
        
        DHDiagnosisTypeViewController *tVC = [[DHDiagnosisTypeViewController alloc] init];
        
        //处理block循环引用问题、内存泄漏
        __weak typeof(self) weakSelf = self;
        tVC.diagnosisTypeBlock = ^(NSString *diagnosisType){
            
            weakSelf.diagnosisType = diagnosisType;
        };
        
        [self.navigationController pushViewController:tVC animated:YES];
    }
}


#pragma mark - 搭建界面
- (void)xhhSetupSubviews {
    
     CGFloat margin = 12;
    CGFloat marginTop = 9;
    /*------------------typeLabel------------------*/
    UILabel *typeLabel = [[UILabel alloc] init];
    self.diseaseTypeLabel = typeLabel;
    typeLabel.text = [NSString stringWithFormat:@"疾病类型：%@疾病",self.diseaseType];
    typeLabel.font = [UIFont systemFontOfSize:14];
    typeLabel.textColor = [UIColor XHH_colorWithHex:0x525252];
    [self.view addSubview:typeLabel];
    
    [typeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view).offset(margin);
        make.top.equalTo(self.view).offset(marginTop + 64);
        
    }];
    
    
    /*------------------tableview------------------*/
    self.view.backgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.96 alpha:1.00];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    
    self.tableView = tableView;
    
    [self.view addSubview:tableView];
    
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.scrollEnabled = NO;
    
    tableView.rowHeight = 44;
    
    [tableView registerClass:[DHArrowTableViewCell class] forCellReuseIdentifier:arrowCellID];
    [tableView registerClass:[DHSelectTableViewCell class] forCellReuseIdentifier:selectCellID];
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view).offset(margin);
        make.right.equalTo(self.view).offset(-margin);

        make.top.equalTo(typeLabel.mas_bottom).offset(marginTop);
        make.bottom.equalTo(self.view).offset(margin*3);
    }];
    
    /*------------------就诊申请------------------*/
    UIButton *applyBtn = [[UIButton alloc] init];
    [applyBtn setTitle:@"就诊申请" forState:UIControlStateNormal];
    [applyBtn setBackgroundColor:[UIColor globalColor]];
    [applyBtn addTarget:self action:@selector(applyForDoctorWithData:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:applyBtn];
    
    
    [applyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view).offset(margin);
        make.right.equalTo(self.view).offset(-margin);
        make.bottom.equalTo(self.view).offset(-margin);
    }];
    
    
    /*------------------医生图标------------------*/
    UIImageView *doctorPic = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"doctorCount"]];
    
    [self.view addSubview: doctorPic];
    
    [doctorPic mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(applyBtn.mas_top).offset(-margin);
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(100, 100));
    }];
    [doctorPic layoutIfNeeded];
    
    
    /*------------------匹配结果------------------*/
    UILabel *countLabel = [[UILabel alloc] init];
    countLabel.text = @"位";
    countLabel.font = [UIFont systemFontOfSize:14];
    countLabel.textColor = [UIColor globalColor];
    [self.view addSubview:countLabel];
    
    
    UILabel *doctorCount = [[UILabel alloc] init];
    self.doctorCountLabel = doctorCount;
    doctorCount.text = @"0";
    doctorCount.font = [UIFont systemFontOfSize:24];
    doctorCount.textColor = [UIColor globalColor];
    [self.view addSubview:doctorCount];
    
    UILabel *textLabel = [[UILabel alloc] init];
    textLabel.text = @"重诊所为您匹配到";
    textLabel.font = [UIFont systemFontOfSize:13];
    textLabel.textColor = [UIColor XHH_colorWithHex:0xbfbfbf];
    [self.view addSubview:textLabel];
    
    
    [countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(doctorPic);
        make.bottom.equalTo(doctorPic.mas_top).offset(-margin);
    }];
    
    [doctorCount mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.baseline.equalTo(countLabel);
        make.right.equalTo(countLabel.mas_left).offset(-margin);
    }];
    
    [textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(countLabel.mas_top).offset(-margin);
        
    }];
}

#pragma mark - 响应事件
//预约须知
- (void)beSpokenNotice {
    
    NSLog(@"预约须知");
}

//就诊申请
- (void)applyForDoctorWithData:(NSString *)data {
    
    if (self.diseaseDetailType == nil) {
        //调用第三方弹出提示框
        [SVProgressHUD showErrorWithStatus:@"请先选择疾病细分"];
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        delay(1.0);
        return;
    }
    
    DHDoctorApplyViewController *doctorApplyVC = [[DHDoctorApplyViewController alloc] init];
    
    [self.navigationController pushViewController:doctorApplyVC animated:YES];
    
}


#pragma mark - Setter
//修改疾病种类
- (void)setDiseaseDetailType:(NSString *)diseaseDetailType {
    
    _diseaseDetailType = diseaseDetailType;
    
    NSIndexPath *tmpPath = [NSIndexPath indexPathForRow:0 inSection:0];
    
    DHChooseDiseaseModel *model = self.chooseDiseaseList[0];
    
    model.descText = diseaseDetailType;
    
    DHArrowTableViewCell *cell = [self.tableView cellForRowAtIndexPath:tmpPath];
    
    cell.chooseDisease = model;
    
    //发送网络请求，匹配医生数量
    [self requestWithParameters:self.parameters];
    
}

//修改治疗方式
- (void)setDiagnosisType:(NSString *)diagnosisType {
    
    _diagnosisType = diagnosisType;
    
    DHChooseDiseaseModel *model = self.chooseDiseaseList[4];
    
    model.descText = diagnosisType;
    
    NSIndexPath *tmpPath = [NSIndexPath indexPathForRow:0 inSection:4];
    
    DHArrowTableViewCell *cell = [self.tableView cellForRowAtIndexPath:tmpPath];
    cell.chooseDisease = model;
    
    //发送网络请求，匹配医生数量
    [self requestWithParameters:self.parameters];
}

//选中的并发症
- (void)setComplicationsArr:(NSArray *)complicationsArr {
    
    _complicationsArr = complicationsArr;
//    NSLog(@"选中的并发症%@",complicationsArr);
    DHChooseDiseaseModel *model = self.chooseDiseaseList[1];
    NSMutableString *stringM = [NSMutableString string];
    [stringM appendString:@"["];
    [stringM appendString:complicationsArr[0]];
    for (NSInteger i = 1; i < complicationsArr.count; i++) {
//        [stringM appendString:complicationsArr[i]];
        [stringM appendFormat:@",%@",complicationsArr[i]];
        
    }
    [stringM appendString:@"]"];
    
    model.descText = stringM.copy;
    model.numberText = [NSString stringWithFormat:@"(共%zd条)",complicationsArr.count];
    
    DHArrowTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    cell.chooseDisease = model;
}

#pragma mark - 是否隐藏治疗选择
- (void)setIsTreated:(BOOL)isTreated {
    
    _isTreated = isTreated;
    
    // 获取要隐藏item的位置
    NSIndexPath *tmpPath = [NSIndexPath indexPathForRow:0 inSection:4];
    if (isTreated) {
        
        [[self.tableView cellForRowAtIndexPath:tmpPath] setHidden:NO];
    }else{
        
        [[self.tableView cellForRowAtIndexPath:tmpPath] setHidden:YES];
    }
}


#pragma mark - 加载数据
- (void)loadData {
    
    DHChooseDiseaseModel *model1 = [[DHChooseDiseaseModel alloc] init];
    model1.descText = @"请选择疾病细分";
    DHChooseDiseaseModel *model2 = [[DHChooseDiseaseModel alloc] init];
    model2.descText = @"请选择并发症";
    DHChooseDiseaseModel *model3 = [[DHChooseDiseaseModel alloc] init];
    model3.descText = @"是否确诊";
    model3.isText = @"已确诊";
    model3.noText = @"症状疑似";
    DHChooseDiseaseModel *model4 = [[DHChooseDiseaseModel alloc] init];
    model4.descText = @"是否接受过治疗";
    model4.isText = @"接受过";
    model4.noText = @"未接受过";
    DHChooseDiseaseModel *model5 = [[DHChooseDiseaseModel alloc] init];
    model5.descText = @"请选择治疗方式";

    self.chooseDiseaseList = @[model1,model2,model3,model4,model5];
}

#pragma mark - 网络请求
/*
 匹配医生数量
 请求地址: http://iosapi.itcast.cn/doctor/matchedDoctorCount.json.php
 请求参数:
 {"ci1_id":1,"ci2_id":3,"ci3_id":3,"diagnosis_type":0,"is_confirmed":1,"user_id":1000089, "has_diagnosis":2}
 */

/**
 网络请求
 */
-(void)requestWithParameters:(NSDictionary *)parameters {
    
    NSString *URLString = @"http://iosapi.itcast.cn/doctor/matchedDoctorCount.json.php";
//    @{@"page":@1,@"page_size":@15,@"ci1_id":@1,@"ci2_id":@3};
    
    [[NetworkTool sharedTool] POSTWithURLStr:URLString parameters:parameters success:^(id responseObject) {
        if (responseObject != nil) {
            //调用第三方弹出提示框
//            [SVProgressHUD showWithStatus:@"正在加载中...."];
//            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
//            delay(1.0);
            //结束刷新
//            delayUpdata(1.0);
            NSNumber *doctor_count = responseObject[@"data"][@"doctor_count"];
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                
                self.doctorCountLabel.text = [doctor_count stringValue];
            }];
        }
    } failed:^(NSError *error) {
        //调用第三方弹出提示框
        [SVProgressHUD showWithStatus:@"您的网络不给力,加载失败!"];
        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
        delay(1.0);
        [self.tableView.mj_header endRefreshing];
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
